import { ref } from 'vue'
import { message } from 'ant-design-vue'
//键盘事件
export default function (tableData, onSelect, emit, inputValue, props) {
  const selectedIndex = ref(0)
  let lastTime = 0
  let nowTime = 0
  const tableBodyDom = document.querySelector('.select-table-style .ant-table-body')
  let scrollHeight = 0
  const onKeyDown = (e) => {
    nowTime = Date.now()
    if (e.keyCode === 40 && selectedIndex.value < tableData.value.length - 1) {
      selectedIndex.value++
      if (selectedIndex.value > 4) {
        scrollHeight = scrollHeight + 30
        tableBodyDom.scrollTo(0, scrollHeight)
      }
    } else if (e.keyCode === 38 && selectedIndex.value > 0) {
      if (selectedIndex.value < 5) {
        scrollHeight = 30
      }
      scrollHeight = scrollHeight - 30
      tableBodyDom.scrollTo(0, scrollHeight)

      selectedIndex.value--
    } else if (e.keyCode === 13) {
      if (nowTime - lastTime <= 100) {
        setTimeout(() => {
          selectedIndex.value = 0
          const selectedRow = tableData.value[0]
          if (selectedRow?.disabled) {
            return message.error('该数据已被禁用')
          }
          selectedRow && onSelect(selectedRow)
          emit('scanCode')
        }, 1000)
        //扫码枪
      } else {
        //键盘输入
        const selectedRow = tableData.value[selectedIndex.value]
        if (selectedRow.disabled) {
          return message.error('该数据已被禁用')
        }
        emit('enter')
        selectedRow && onSelect(selectedRow)
      }
    } else if (e.keyCode === 8) {
      //删除键
      emit('delete')
      if (props.multiple) {
        // const str = inputValue.value.slice(0, -1)
        let str = inputValue.value
        if (str.substr(-1) === '，') {
          str = str.substring(0, str.length - 1)
        }
        inputValue.value = str.substring(0, str.lastIndexOf('，') + 1)
      }
    }
    lastTime = nowTime
  }
  const keyboardRowClassName = (index) => {
    return index === selectedIndex.value ? 'table-row-selected' : ''
  }
  return { onKeyDown, keyboardRowClassName }
}
